<?php
declare (strict_types = 1);

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Db;

class Report extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('report')
            ->setDescription('the report command');        
    }

    protected function execute(Input $input, Output $output)
    {
    	// 指令输出
        //每个月的6号生成上个月的报表
        //生成门店的财务报表
        //BusinessMoeny   商家收支明细模型
        $BusinessMoeny_model = app('app\api\model\BusinessMoeny');
        //Business   商家模型
        $Business_model = app('app\api\model\Business');
        $Business_data = $Business_model->select()->toArray();
        //BusinessReport   商家财务报表模型
        $BusinessReport_model = app('app\api\model\BusinessReport');
        //BusinessReportDetailed  报表明细
        $BusinessReportDetailed_model = app('app\api\model\BusinessReportDetailed');
        //BusinessMoneyType  报表事项模型
        $BusinessMoneyType_model = app('app\api\model\BusinessMoneyType');
        $BusinessMoneyType_data = $BusinessMoneyType_model->order('id asc')->select()->toArray();
        $sr_data_ids = $BusinessMoneyType_model->where('type',1)->select()->toArray();
        $sr_ids = [];
        foreach ($sr_data_ids as $k=>$v){
            $sr_ids[] = $v['id'];
        }
        //收入类型事项ID
        $sr_ids = implode(',',$sr_ids);
        $zc_data_ids = $BusinessMoneyType_model->where('type',2)->select()->toArray();
        $zc_ids = [];
        foreach ($zc_data_ids as $k=>$v){
            $zc_ids[] = $v['id'];
        }
        //支出类型事项ID
        $zc_ids = implode(',',$zc_ids);
        //获取上个月的起始截止日期
        $thismonth = date('m');
        $thisyear = date('Y');
        if ($thismonth == 1) {
            $lastmonth = 12;
            $lastyear = $thisyear - 1;
        } else {
            $lastmonth = $thismonth - 1;
            $lastyear = $thisyear;
        }
        $lastStartDay = $lastyear . '-' . $lastmonth . '-1';
        $lastEndDay = $lastyear . '-' . $lastmonth . '-' . date('t', strtotime($lastStartDay));

        $a_time = $lastStartDay.' 00:00:00';//上个月的月初时间戳
        $b_time = $lastEndDay. ' 23:59:59';//上个月的月末时间戳
        //年-月
        if(date('m') == 1){
            $year = date('Y') -1;
            $month = 12;
        }else{
            $year = date('Y');
            $month = date('m');
        }
        //对所有的商家进行处理
        foreach ($Business_data as $k=>$v)
        {
            //新增报表ID
            $business_report_id = Db::name('business_report')->insertGetId([
                'business_id'=>$v['id'],
                'year'=>$year,
                'month'=>$month,
                'money_percentage'=>0
            ]);
            $arr = [];
            foreach ($BusinessMoneyType_data as $kk=>$vv)
            {

                $money = $BusinessMoeny_model->where([
                    ['business_id','=',$v['id']],
                    ['date','>=',$a_time],
                    ['date','<=',$b_time],
                    ['business_money_type_id','=',$vv['id']]
                ])->sum('money');
                //获取上月同类型事项的数据，比较获取增幅
                $sc_detailed = $BusinessReportDetailed_model->where([
                    ['create_time','<',date('Y-m-d')],
                    ['business_id','=',$v['id']],
                    ['business_money_type_id','=',$vv['id']]
                ])->order('id desc')->find();
                //获得幅度与上升下降状态
                if(!empty($sc_detailed) && !empty($sc_detailed->toArray()))
                {
                    $sc_detailed = $sc_detailed->toArray();
                    $detailed_zf = ceil(($money/$sc_detailed['money']*10000))/100;
                    if($money>$sc_detailed['money']){
                        $detailed_status = 1;
                    }else{
                        $detailed_status = 2;
                    }
                }else{
                    $detailed_zf = 0;
                    $detailed_status = 1;
                }
                //添加明细数据
                Db::name('business_report_detailed')->insert([
                    'business_report_id'=>$business_report_id,
                    'business_money_type_id'=>$vv['id'],
                    'money'=>$money,
                    'status'=>$detailed_status,
                    'fd'=>$detailed_zf,
                    'create_time'=>date('Y-m-d H:i:s'),
                    'update_time'=>date('Y-m-d H:i:s')
                ]);
            }
            //明细数据添加完成后，查询明细数据汇总，计算出报表的汇总数据
            //合计收入金额
            $sr_money = $BusinessReportDetailed_model->where([
                ['business_report_id','=',$business_report_id],
                ['business_money_type_id','in',$sr_ids]
            ])->sum('money');
            //合计支出金额
            $zc_money = $BusinessReportDetailed_model->where([
                ['business_report_id','=',$business_report_id],
                ['business_money_type_id','in',$zc_ids]
            ])->sum('money');
            //获取当次循环的商户上次报表记录
            $sc_report_data = $BusinessReport_model->where([
                ['business_id','=',$v['id']],
                ['id','<',$business_report_id]
            ])->order('id desc')->find();
            //记录存在就进行比较，不存在就直接添加
            if(!empty($sc_report_data) && !empty($sc_report_data->toArray()))
            {
                $sy_money = $sr_money - $zc_money;
                $sc_report_data = $sc_report_data->toArray();
                //结算类型 1=增长  2=减少
                if($sy_money >= $sc_report_data['money']){
                    $money_status = 1;
                }else{
                    $money_status = 2;
                }
                //结算百分比
                $money_percentage = ceil(($sy_money/$sc_report_data['money']*10000))/100;
                //收入增幅类型
                if($sr_money >= $sc_report_data['income']){
                    $income_status = 1;
                }else{
                    $income_status = 2;
                }
                //收入百分比
                $income_percentage = ceil(($sy_money/$sc_report_data['income']*10000))/100;
                //支出增幅类型
                if($zc_money >= $sc_report_data['expenditure']){
                    $expenditure_status = 1;
                }else{
                    $expenditure_status = 2;
                }
                //支出百分比
                $expenditure_percentage = ceil(($zc_money/$sc_report_data['expenditure']*10000))/100;
                $report_update = [
                    'id'=>$business_report_id,
                    'money_status'=>$money_status,
                    'money_percentage'=>$money_percentage,
                    'money'=>$sy_money,
                    'income'=>$sr_money,
                    'expenditure'=>$sr_money,
                    'income_status'=>$income_status,
                    'expenditure_status'=>$expenditure_status,
                    'income_percentage'=>$income_percentage,
                    'expenditure_percentage'=>$expenditure_percentage,
                    'create_time'=>date('Y-m-d H:i:s'),
                    'update_time'=>date('Y-m-d H:i:s')
                ];
                Db::name('business_report')->save($report_update);
            }else{
                //直接组装添加
                $sy_money = $sr_money - $zc_money;
                $report_update = [
                    'id' => $business_report_id,
                    'money_status'=>1,
                    'money_percentage'=>0,
                    'money'=>$sy_money,
                    'income'=>$sr_money,
                    'expenditure'=>$sr_money,
                    'income_status'=>1,
                    'expenditure_status'=>1,
                    'income_percentage'=>0,
                    'expenditure_percentage'=>0,
                    'create_time'=>date('Y-m-d H:i:s'),
                    'update_time'=>date('Y-m-d H:i:s')
                ];
                Db::name('business_report')->save($report_update);
            }
        }
        //生成DM【主持人】的每月报表
        //BusinessHost  主持人模型
        $BusinessHost_model = app('app\api\model\BusinessHost');
        $BusinessHost_data = $BusinessHost_model->with(['business'])->select()->toArray();
        //BusinessHostLog  主持人记录模型
        $BusinessHostLog_model = app('app\api\model\BusinessHostLog');
        //BusinessHostReport  主持人报表模型
        $BusinessHostReport_model = app('app\api\model\BusinessHostReport');
        //BusinessHostSetting  门店主持人提现设置模型
        $BusinessHostSetting_model = app('app\api\model\BusinessHostSetting');
        foreach ($BusinessHost_data as $k=>$v){
            //门店已被删除的主持人不需要再生成报表
            if(empty($v['business'])){
                continue;
            }
            $setting_data = $BusinessHostSetting_model->where([
                ['business_id','=',$v['business_id']]
            ])->find();
            if(!empty($setting_data) && !empty($setting_data->toArray())){
                $setting_data = $setting_data->toArray();
                //查出日期范围内的3个场次对应的次数-小计
                $data = [];
                $data['xw_num'] = $BusinessHostLog_model->where([
                    ['business_id','=',$v['business']['id']],
                    ['business_host_id','=',$v['id']],
                    ['date','>=',$a_time],
                    ['date','<=',$b_time]
                ])->sum('xw_num');
                $data['xw_money'] = ($data['xw_num'] * $setting_data['xw_money']);
                $data['ws_num'] = $BusinessHostLog_model->where([
                    ['business_id','=',$v['business']['id']],
                    ['business_host_id','=',$v['id']],
                    ['date','>=',$a_time],
                    ['date','<=',$b_time]
                ])->sum('ws_num');
                $data['ws_money'] = ($data['ws_num'] * $setting_data['ws_money']);
                $data['xx_num'] = $BusinessHostLog_model->where([
                    ['business_id','=',$v['business']['id']],
                    ['business_host_id','=',$v['id']],
                    ['date','>=',$a_time],
                    ['date','<=',$b_time]
                ])->sum('xx_num');
                $data['xx_money'] = ($data['xx_num'] * $setting_data['xx_money']);
                $data['business_id'] = $v['business_id'];
                $data['business_host_id'] = $v['id'];
                $data['year'] = $year;
                $data['month'] = $month;
                $data['min_money'] = $v['min_money'];
                $data['money'] = ($data['xw_money']+$data['ws_money']+$data['xx_money']);
                $data['create_time'] = date('Y-m-d H:i:s');
                $data['update_time'] = date('Y-m-d H:i:s');
                //添加报表数据
                Db::name('business_host_report')->insert($data);
            }else{
                //如果为空表示还没设置提成，不会生成报表
                continue;
            }

        }
    	$output->writeln('report 生成报表成功');
    }
}
